<?php
/**
 * @property SessionComponent $Session
 *
 * $cart = array(
 *      'totalPrice' => total_price,
 *      'items' =>array(
 *          '0' => array(       //product_id
 *              'name' => 'product name'
 *              'subPrice' => sub price (product)
 *              'sizes' => array(
 *                  '0' => array(       //size_id
 *                      'name' => 'size name'
 *                      'quantity' => quantity per size
 *                      'price'     => price
 *                  )
 *              )
 *          )
 *      ),
 * );
 */
 /**
  * @property SessionComponent $Session
  */
class CartComponent extends Object{
    public $components = array('Session');
    /**
     *
     * @var Order
     */
    public $Order;

    /**
     *
     * @var PrderProduct
     */
    public $OrdersProduct;

    /**
     *
     * @var Product
     */
    public $Product;

    /**
     *
     * @var Size
     */
    public $Size;

    /**
     *
     * @var User
     */
    public $User;
    /**
     *
     * @var AppController
     */
    public $controller;

    /**
     *
     * @var array
     */
    private $cart = array();

    public function initialize(AppController $controller, $setting = array())
    {
        $this->controller = $controller;

        if($this->Session->check('cart')){
            $this->cart = $this->Session->read('cart');
        }
        else{
            $this->cart = array(
                'totalPrice' => 0,
                'items' => array()
            );
        } 



        $this->Order = ClassRegistry::init('Order');
        $this->OrdersProduct = ClassRegistry::init('OrdersProduct');
        $this->Product = ClassRegistry::init('Product');
        $this->Size = ClassRegistry::init('Size');
        $this->User = ClassRegistry::init('User');
    }

    public function addToCart($size_id = null, $quantity = 0){
        if(!$size_id) {
            $this->Session->setFlash("Product not exists!");
            return false;
        }

        if(!$quantity) {
            $this->Session->setFlash("Please check the quantity!");
            return false;
        }
        
        $size = $this->Size->read('', $size_id);
        if(!$size){
            return false;
        }

        $product = $size['Product'];

        $price = $size['Size']['price'] * $quantity;

        /**
         * Ha még üres a kosár, létre kell hozni az items tömböt és a totalPrice
         * számlálót
         */

         if (!array_key_exists('totalPrice', $this->cart)) {
             $this->cart['totalPrice'] = 0;
         }

         if (!array_key_exists('items', $this->cart)) {
            $this->cart['items'] = array();
         }

        /*
         * ha a termék még nincs a kosárban, felvesszuk a terméket
         */
        if (!array_key_exists($product['id'], $this->cart['items'])) {
            $this->_addProductToCart($product);
        }

        /*
         * felvesszük a méretet a termékhez és frissítjük a költség
         * számlálókat. Ha ilyen méret nincs a kosárban betesszük, ha van
         * hozzáadjuk a meglevőhöz
         */
        if (!array_key_exists($size_id, $this->cart['items'][$product['id']]['sizes'])){
            $this->cart['items'][$product['id']]['sizes'][$size_id] = array(
                'name' => $size['Size']['value'],
                'quantity' => $quantity,
                'price'     => $price,
            );
        }
        else {
            $this->cart['items'][$product['id']]['sizes'][$size_id] = array(
                'name' => $size['Size']['value'],
                'quantity' => $this->cart['items'][$product['id']]['sizes'][$size_id]['quantity'] += $quantity,
                'price'     => $this->cart['items'][$product['id']]['sizes'][$size_id]['price'] += $price,
            );
        }

        $this->cart['totalPrice'] += $price;
        $this->cart['items'][$product['id']]['subPrice'] += $price;

         return true;
    }

    public function checkOut($user_id = null){
        if(is_null($user_id)){
            $user_id = $this->controller->Auth->user('id');
        }

        $user = $this->User->find('first', array('conditions'=>array('User.id'=>$user_id)));
        if(!$user){
            $this->Session->setFlash('User not found');
            return false;
        }

        $order["Order"] = array(
            "company"  => $user["User"]["company"],
            "email"    => $user["User"]["email"],
            "name"     => $user["User"]["name"],
            "address"  =>"Transport: ".$this->User->TransportAddress->toLine($user)." ".
            "Invoice: ".$this->User->InvoiceAddress->toLine($user),
            "user_id"  => $this->controller->Auth->user("id")
        );

        $orderProducts = array();
        foreach($this->cart['items'] as $product){
            $orderProducts = array_merge($orderProducts,$this->Order->OrdersProduct->fromCart($product));
        }

        $this->Order->create();
        $order['OrdersProduct'] = $orderProducts;

        return ($this->Order->saveAll($order)) ? $order : false ;
    }

    public function beforeRender($controller){
        $controller->set('cart', $this->cart);
        $this->Session->write('cart', $this->cart);
    }

    public function beforeRedirect(&$controller, $url, $status=null, $exit=true) {
	$this->beforeRender($controller);
        //return true;
    }


    private function _addProductToCart($product){
        $this->cart['items'][$product['id']] = array(
            'name' => $product['product_name'],
            'subPrice' => 0,
            'sizes' => array()
        );
    }

    public function delete($pid, $sid){
        if (array_key_exists($pid, $this->cart['items'])) {
            if (array_key_exists($sid, $this->cart['items'][$pid]['sizes'])) {
                $price = $this->cart['items'][$pid]['sizes'][$sid]['price'];
                $this->cart['items'][$pid]['subPrice'] -= $price;
                $this->cart['totalPrice'] -= $price;
                unset($this->cart['items'][$pid]['sizes'][$sid]);
                if(count($this->cart['items'][$pid]['sizes']) == 0){
                    unset($this->cart['items'][$pid]);
                }
            }
        }
    }

    public function deleteCart(){
        $this->Session->delete('cart');
        $this->cart = array(
                'totalPrice' => 0,
                'items' => array()
        );
        $this->Session->write('cart', $this->cart);
    }
}

?>
